--------------UART ------------
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.std_logic_unsigned.ALL;
USE ieee.std_logic_arith.ALL;

entity uart is
	port (
		reset		:in  std_logic;
		clk		:in  std_logic;
		---rx signals---
		rx_data	:out std_logic_vector (7 downto 0);
		rx_in		:in  std_logic;
		rx_busy	:out std_logic;
		---tx signals------
		tx_data	:in std_logic_vector (7 downto 0);
		tx_out	:out  std_logic;
		tx_busy	:out std_logic;
		tx_send	:in std_logic
		);
end uart;
architecture rtl of uart is
	signal rx_count, rx_delay, tx_count, tx_delay: integer;
	signal rx_reading, tx_sending : std_logic;
	signal rx_prl_data, tx_prl_data: std_logic_vector (7 downto 0);
begin
-- read process---
	process (clk, reset)
	
	begin
	if (clk = '1' and clk'event) then
		if (reset = '1') then
			rx_prl_data <= "00000000";
			rx_data <= "00000000";
			rx_delay <= 0;
			rx_count <= 0;
			rx_reading <= '0';
			rx_busy <= '0';
		else
			if (rx_reading = '0' and rx_in = '0') then
				rx_reading <= '1';
				rx_busy <= '1';
				rx_delay <= 0;
				rx_data <= "00000000";
				rx_prl_data <= "00000000";
			else
				if (rx_reading = '1' and rx_delay < 434) then
				rx_delay <= rx_delay +1;
				else
					if (rx_reading = '1' and rx_count < 8) then
						rx_prl_data <= rx_prl_data (6 downto 0) & rx_in;
						rx_count <= rx_count + 1;
						rx_delay <= 0;
					else
						rx_count <= 0;
						rx_delay <= 0;
						rx_busy <= '0';
						rx_data <= rx_prl_data;
						rx_reading <= '0';
					end if;
				end if;
			end if;
		end if;
	end if;
	end process;
	
	----- transmit process
	process (clk, reset)
	begin
	if (clk = '1' and clk'event) then
		if (reset = '1') then
			tx_out <= '1';
			tx_delay <= 0;
			tx_count <= 0;
			tx_busy <= '0';
			tx_sending <= '0';
		else
			if (tx_send = '1' and tx_sending = '0') then
				tx_out <= '0';
				tx_delay <= 0;
				tx_count <= 0;
				tx_busy <= '1';
				tx_sending <= '1';
				tx_prl_data <= tx_data;
			else
				if (tx_sending = '1' and tx_delay < 434) then
					tx_delay <= tx_delay +1;
				else
					if (tx_sending = '1' and tx_count < 8) then
						tx_out <= tx_prl_data(7-tx_count);
						tx_count <= tx_count +1;
						tx_delay <= 0;
					else
						tx_out <= '1';
						tx_delay <= 0;
						tx_count <= 0;
						tx_busy <= '0';
						if (tx_delay = 434) then
							tx_sending <= '0';
						end if;
					end if;
				end if;
			end if;
		end if;
	end if;
	end process;
end rtl;